"""
*    pyToGmaps 0.1
*    Copyright (C) 2013 Max Tangelder <maxovitsj+pytogmaps@gmail.com>
*
*    This program is based on 'pymaps' https://code.google.com/p/pymaps/
*
*    Biggest change is conversion to Google Maps API v3 and simplification.
*    Feel free to edit / add / remove things :-)
*
*    This program is free software; you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation; either version 2 of the License, or
*    (at your option) any later version.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU General Public License
*    along with this program; if not, write to the Free Software
*    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
"""

class Map:
    def __init__(self,id="map",markerList=None):
        self.id             = id # the map id
        self.center         = (23.563987,15.644531) # default center on around Libya at zoom level 2 this is around the center of the map
        self.zoom           = 2 # zoom level 2 gives a nice global view
        self.navcontrols    = True # show the Google navigation controls?
        self.mapcontrols    = True # show the Google map controls?
        self.visRefresh     = "true" # Use the new 'refreshed' visual style?
        if markerList == None:
            self.markers = [] #empty list for the markers
        else:
            self.markers = markerList
    
    def __str__(self):
        return self.id
    
    def addMarker(self, marker):
        """ Add a marker (latitude, longitude, html content for info window) """
        self.markers.append(marker)

class PyToGMap:
    def __init__(self, apiKey=None, maplist=None):
        self.apiKey = "!<GOOGLE MAPS API v3 KEY GOES HERE>!" # set your Google Maps API v3 key here, if you want to track stuff / or if you're using this for commercial purposes!
        if maplist == None:
            self.maps = [Map()]
        else:
            self.maps = maplist
        
    def __str__(self):
        return "PyToGMap"
    
    def _mapOptions(self, gmap):
        options = """google.maps.visualRefresh = %s;
                var mapOptions = 
                {
                    center: new google.maps.LatLng(%f,%f),
                    zoom: %d,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };""" % (self.maps[0].visRefresh, self.maps[0].center[0], self.maps[0].center[1], self.maps[0].zoom)
        return options
    
    def _genMapjs(self):
        code = "var map = new google.maps.Map(document.getElementById(\"map-canvas\"), mapOptions);"
        return code
    
    def _genMarkers(self, map):
        code = "%s_markers = %s;\n" % (self.maps[0].id, self.maps[0].markers)
        code = code + """
                for (var i in map_markers)
                {
                    var pos = new google.maps.LatLng(map_markers[i][0], map_markers[i][1]);
                    var marker = new google.maps.Marker(
                    {
                        position: pos,
                        map: map,
                        animation: google.maps.Animation.DROP,
                        title: map_markers[i][2]
                    });
                    addIW(marker, i);
                };"""
        return code
    
    def _genIW(self, map):
        code = """
                function addIW(marker)
                {
                    var message = map_markers[i][3];
                    var iw = new google.maps.InfoWindow({content: message});
                    google.maps.event.addListener(marker, 'click', function()
                    {
                        iw.open(map, marker);
                    });
                };
        """
        return code
    
    def genJS(self):
        #Generate and return the complete javascript to render the map
        
        self.js = """<script type=\"text/javascript\" src=\"https://maps.googleapis.com/maps/api/js?key=%s&sensor=false">
        </script>
        <script type=\"text/javascript\">
            function initialize()
            {
                %s 
                %s
                %s
                %s
            };
            google.maps.event.addDomListener(window, 'load', initialize);
        </script>
        """ % (self.apiKey, self._mapOptions(map), self._genMapjs(), self._genMarkers(map), self._genIW(map))
        return self.js
    
    def genHTML(self):
        self.html = """<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
        <link href="main.css" rel="stylesheet" type="text/css">    
        %s
    </head>
    <body>
        <div id="map-canvas"/>
    </body>
</html>
""" % self.genJS()
        return self.html

if __name__ == "__main__":
    #Example:
    g = PyToGMap()
    pic1 = [33.8754608154,-116.301619602,"Holiday_1.jpg","<img src='Holiday_1.jpg' width='250' height='150'>"] #make a new pic: lat, lon, html content for infowindow
    g.maps[0].addMarker(pic1) #add it to the marker list of the map
    
    open('pytogmapstest.html', 'wb').write(g.genHTML()) #generate html file
    